<template>
  <div class="weather-app">
    <header class="app-header" v-if="isLoggedIn && currentView !== 'initial' && currentView !== 'login' && currentView !== 'register'">
      <div class="header-left">
        <span v-if="currentView === 'home'">天气预报</span>
        <span v-else-if="currentView === 'favorites'">我的收藏</span>
        <span v-else-if="currentView === 'history'">历史天气</span>
        <span v-else-if="currentView === 'profile'">个人中心</span>
      </div>
      <div class="header-right" v-if="currentView === 'home'">
        <input
          type="text"
          v-model="searchQuery"
          @keyup.enter="searchCity"
          placeholder="搜索城市..."
          class="search-input"
        >
        <button @click="searchCity" class="search-button">搜索</button>
      </div>
    </header>

    <main class="app-main-content" v-if="isLoggedIn">
      <div v-if="currentView === 'home'">
        <div class="weather-display" v-if="currentWeather">
          <h2>{{ currentWeather.city_name }} ({{ currentWeather.province }})</h2>
          <p v-if="currentWeather.adcode">区域编码: {{ currentWeather.adcode }}</p>
          <div class="weather-icon">{{ getWeatherIconClass(currentWeather.description) }}</div>
          <div class="weather-info">
            <p class="temperature">{{ currentWeather.temperature }}°C</p>
            <p class="description">{{ currentWeather.description }}</p>
            <p class="wind">风向: {{ currentWeather.winddirection }} 风力: {{ currentWeather.windpower }}</p>
            <p class="humidity">湿度: {{ currentWeather.humidity }}%</p>
            <p class="date">{{ formatDateTime(currentWeather.reporttime) }}</p>
          </div>
        </div>
        <div v-else-if="locationLoading">
          <p>正在获取当前定位及天气信息...</p>
        </div>
        <div v-else-if="locationError">
          <p>{{ locationError }}</p>
        </div>
        <div v-else>
          <p>请搜索一个城市来查看天气。</p>
        </div>

        <!-- 添加未来天气和温度折线图 -->
        <div class="forecast-section" v-if="forecastWeather">
          <h3>未来天气预报</h3>
          <div class="forecast-list">
            <div v-for="(forecast, index) in forecastWeather.forecasts" :key="index" class="forecast-item">
              <div class="forecast-date">{{ formatDateShort(forecast.date) }} ({{ forecast.week }})</div>
              <div class="forecast-weather">
                <div class="day-weather">
                  <span class="weather-icon">{{ getWeatherIconClass(forecast.day_weather) }}</span>
                  <span>白天: {{ forecast.day_weather }}</span>
                  <span class="temperature">{{ forecast.day_temp }}°C</span>
                  <span class="wind">风向: {{ forecast.day_wind }} 风力: {{ forecast.day_power }}</span>
                </div>
                <div class="night-weather">
                  <span class="weather-icon">{{ getWeatherIconClass(forecast.night_weather) }}</span>
                  <span>夜晚: {{ forecast.night_weather }}</span>
                  <span class="temperature">{{ forecast.night_temp }}°C</span>
                  <span class="wind">风向: {{ forecast.night_wind }} 风力: {{ forecast.night_power }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 温度折线图 -->
          <div class="temperature-chart">
            <h3>温度变化趋势</h3>
            <v-chart class="chart" :option="chartOption" autoresize />
          </div>
        </div>

        <!-- AI Suggestions Section -->
        <div class="ai-suggestions-section">
          <h3>AI出行计划与生活建议</h3>
          <div v-if="aiSuggestions">
            <div v-if="aiSuggestions.travel_plan && Object.keys(aiSuggestions.travel_plan).length > 0">
              <h4>出行计划</h4>
              <ul>
                <li v-for="(plan, date) in aiSuggestions.travel_plan" :key="'travel-' + date"><strong>{{ date }}:</strong> {{ plan }}</li>
              </ul>
            </div>
            <div v-if="aiSuggestions.life_suggestions">
              <h4>生活建议</h4>
              <ul>
                <li v-if="aiSuggestions.life_suggestions.general"><strong>通用:</strong> {{ aiSuggestions.life_suggestions.general }}</li>
                <template v-if="aiSuggestions.life_suggestions.specific_days && Object.keys(aiSuggestions.life_suggestions.specific_days).length > 0">
                  <li v-for="(suggestion, date) in aiSuggestions.life_suggestions.specific_days" :key="'life-' + date"><strong>{{ date }}:</strong> {{ suggestion }}</li>
                </template>
              </ul>
            </div>
          </div>
          <button @click="getAiSuggestions" class="get-ai-suggestions-button" :disabled="aiLoading">
            <span v-if="aiLoading" class="loading-spinner"></span>
            <span v-else>获取AI建议</span>
          </button>
        </div>
      </div>

      <div v-if="currentView === 'favorites'" class="page-content">
        <div class="favorites-header">
          <h3>我的收藏</h3>
          <button @click="openAddCityModal" class="add-city-button">添加城市</button>
        </div>
        <div v-if="favoriteCities.length > 0" class="favorite-cities-list">
          <div v-for="city in favoriteCities" :key="city.city_id" class="favorite-city-item">
            <span>{{ city.name }}</span>
            <button @click="viewFavoriteCityWeather(city.city_id)">查看天气</button>
          </div>
        </div>
        <p v-else>您还没有收藏任何城市。</p>
      </div>

      <div v-if="currentView === 'history'" class="page-content history-section">
        <h3>历史天气</h3>
        <!-- 移除手动搜索和查询按钮，历史天气数据将自动显示 -->
        <!-- <div class="history-input-group">
          <input type="text" v-model="location" placeholder="输入城市" @keyup.enter="fetchHistoricalWeather">
          <input type="date" v-model="date">
          <button @click="fetchHistoricalWeather">查询</button>
        </div> -->

        <div v-if="historicalWeather && historicalWeather.historicalWeather && historicalWeather.historicalWeather.length > 0" class="historical-chart-container">
          <v-chart class="historical-chart" :option="historicalChartOption" autoresize />
        </div>

        <p v-else-if="errorMessage" class="history-error-message">{{ errorMessage }}</p>
        <!-- 移除旧的提示信息，因为数据将自动加载 -->
        <!-- <p v-else-if="!historicalWeather" class="info-message">请输入城市并点击查询，查看历史天气数据。</p> -->
        <p v-else class="info-message">正在加载历史天气数据...</p>
      </div>

      <div v-if="currentView === 'profile'" class="page-content profile-container">
        <div class="profile-header">
          <h2>个人中心</h2>
        </div>
        
        <div class="profile-avatar">
          <img :src="previewAvatarUrl || userProfile.avatar_url || '/uploads/avatars/default-avatar.png'" alt="头像" class="avatar-image">
          <label for="avatar-upload-input" class="avatar-upload-overlay">
            <input type="file" id="avatar-upload-input" ref="avatarInput" @change="handleAvatarFileChange" class="avatar-upload-input" accept="image/*">
            <span>+</span>
          </label>
          <button v-if="selectedAvatarFile" @click="uploadUserAvatar" class="profile-upload-button">上传头像</button>
        </div>

        <div class="profile-item">
          <label>昵称:</label>
          <div class="editable-field">
            <span v-if="!isEditingUsername">{{ userProfile.username }}</span>
            <input v-else type="text" v-model="editableUsername" class="edit-input">
            <button v-if="!isEditingUsername" @click="startEditUsername" class="edit-button">编辑</button>
            <template v-else>
              <button @click="saveUsername" class="save-button">保存</button>
              <button @click="cancelEditUsername" class="cancel-button">取消</button>
            </template>
          </div>
        </div>

        <div class="profile-item">
          <label>定位城市:</label>
          <span>{{ autoDetectedCity || '未定位' }}</span>
        </div>

        <div class="profile-item">
          <label>邮箱:</label>
          <span>{{ userProfile.email }}</span>
        </div>

        <button @click="openChangePasswordModal" class="change-password-button">修改密码</button>
        <button @click="logout" class="logout-button">退出登录</button>
      </div>
    </main>

    <nav class="app-navbar" v-if="isLoggedIn && currentView !== 'initial' && currentView !== 'login' && currentView !== 'register'">
      <button @click="goToHome" :class="{ active: currentView === 'home' }">主页</button>
      <button @click="goToFavorites" :class="{ active: currentView === 'favorites' }">我的收藏</button>
      <button @click="goToHistory" :class="{ active: currentView === 'history' }">历史天气</button>
      <button @click="goToProfile" :class="{ active: currentView === 'profile' }">我的信息</button>
    </nav>

    <!-- 初始登录/注册按钮 -->
    <div class="auth-container" v-if="currentView === 'initial'">
      <div class="welcome-text">欢迎使用天气预报</div>
      <div class="auth-buttons">
        <button @click="currentView = 'login'">登录</button>
        <button @click="currentView = 'register'">注册</button>
      </div>
    </div>

    <!-- 登录表单 -->
    <div class="auth-container" v-if="currentView === 'login'">
      <h2>登录</h2>
      <form @submit.prevent="login">
        <div class="form-group">
          <input type="email" v-model="loginForm.email" placeholder="邮箱" required>
        </div>
        <div class="form-group">
          <input type="password" v-model="loginForm.password" placeholder="密码" required>
        </div>
        <button type="submit">登录</button>
        <button type="button" @click="currentView = 'register'">去注册</button>
        <button type="button" @click="goBack">返回</button>
      </form>
    </div>

    <!-- 注册表单 -->
    <div class="auth-container" v-if="currentView === 'register'">
      <h2>注册</h2>
      <form @submit.prevent="register">
        <div class="form-group">
          <input type="text" v-model="registerForm.username" placeholder="用户名" required>
        </div>
        <div class="form-group">
          <input type="email" v-model="registerForm.email" placeholder="邮箱" required>
        </div>
        <div class="form-group">
          <input type="password" v-model="registerForm.password" placeholder="密码" required>
        </div>
        <button type="submit">注册</button>
        <button type="button" @click="currentView = 'login'">去登录</button>
        <button type="button" @click="goBack">返回</button>
      </form>
    </div>

    <!-- 添加城市模态框 -->
    <div class="add-city-modal" v-if="showAddCityModal">
      <div class="modal-content">
        <span class="close-button" @click="closeAddCityModal">&times;</span>
        <h2>添加城市</h2>
        <input
          type="text"
          v-model="addCitySearchQuery"
          @keyup.enter="searchCityToAdd"
          placeholder="搜索城市..."
        >
        <button @click="searchCityToAdd">搜索</button>
        <div v-if="addCitySearchResults.length > 0">
          <h3>搜索结果</h3>
          <div v-for="city in addCitySearchResults" :key="city.city_id" class="city-item">
            <span>{{ city.name }}</span>
            <button @click="addFavoriteCity(city.city_id)">添加</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码模态框 -->
    <div class="change-password-modal" v-if="showChangePasswordModal">
      <div class="modal-content">
        <span class="close-button" @click="closeChangePasswordModal">&times;</span>
        <h2>修改密码</h2>
        <form @submit.prevent="changePassword">
          <div class="form-group">
            <label for="old-password">旧密码:</label>
            <input type="password" id="old-password" v-model="oldPassword" required>
          </div>
          <div class="form-group">
            <label for="new-password">新密码:</label>
            <input type="password" id="new-password" v-model="newPassword" required>
          </div>
          <div class="form-group">
            <label for="confirm-new-password">确认新密码:</label>
            <input type="password" id="confirm-new-password" v-model="confirmNewPassword" required>
          </div>
          <button type="submit" class="save-button">确认修改</button>
          <button type="button" @click="closeChangePasswordModal" class="cancel-button">取消</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { weatherService } from '../services/weather';
import ECharts from 'vue-echarts';
import { use } from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { userService } from '../services/user';
import { aiService } from '../services/aiService';

// 注册 ECharts 组件
use([
  LineChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  CanvasRenderer
]);

export default {
  name: 'WeatherApp',
  components: {
    'v-chart': ECharts,
  },
  data() {
    return {
      cities: [],
      selectedCity: null,
      currentWeather: null,
      isLoggedIn: false,
      userProfile: { username: '', email: '', avatar_url: null },
      currentView: 'initial',
      loginForm: {
        email: '',
        password: ''
      },
      registerForm: {
        username: '',
        email: '',
        password: ''
      },
      locationLoading: false,
      locationError: null,
      autoDetectedCity: null,
      searchQuery: '',
      forecastWeather: null,
      showAddCityModal: false,
      addCitySearchQuery: '',
      addCitySearchResults: [],
      chartOption: {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['最高温度', '最低温度']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} °C'
          }
        },
        series: [
          {
            name: '最高温度',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: {
              color: '#ff7f50'
            }
          },
          {
            name: '最低温度',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: {
              color: '#4169e1'
            }
          }
        ]
      },
      favoriteCities: [],
      showChangePasswordModal: false,
      oldPassword: '',
      newPassword: '',
      confirmNewPassword: '',
      selectedAvatarFile: null,
      previewAvatarUrl: null,
      editableUsername: '',
      isEditingUsername: false,
      aiSuggestions: null,
      aiLoading: false,
      // Historical weather data properties
      location: '',
      date: new Date().toISOString().slice(0, 10), // Current date in YYYY-MM-DD format
      historicalWeather: null,
      errorMessage: '',
    };
  },
  computed: {
    historicalChartOption() {
      if (!this.historicalWeather || !this.historicalWeather.historicalWeather || this.historicalWeather.historicalWeather.length === 0) {
        return {};
      }
      const dates = this.historicalWeather.historicalWeather.map(item => item.date);
      const temperatures = this.historicalWeather.historicalWeather.map(item => item.temperature);
      const weatherConditions = this.historicalWeather.historicalWeather.map(item => item.weather_condition);

      return {
        title: {
          text: `${this.historicalWeather.city_name} 历史气温趋势`, // Title updated
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 18,
          },
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            const dataIndex = params[0].dataIndex;
            const date = dates[dataIndex];
            const temp = temperatures[dataIndex];
            const condition = weatherConditions[dataIndex];
            return `日期: ${date}<br/>气温: ${temp}°C<br/>天气: ${condition}`;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ccc',
          borderWidth: 1,
          textStyle: {
            color: '#333',
          },
          extraCssText: 'box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);'
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            color: '#666',
          },
          axisLine: {
            lineStyle: {
              color: '#ccc',
            },
          },
        },
        yAxis: {
          type: 'value',
          name: '气温 (°C)',
          axisLabel: {
            color: '#666',
            formatter: '{value} °C'
          },
          axisLine: {
            lineStyle: {
              color: '#ccc',
            },
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee',
            },
          },
        },
        series: [
          {
            name: '气温',
            type: 'line',
            data: temperatures,
            smooth: true,
            itemStyle: {
              color: '#5470C6'
            },
            lineStyle: {
              width: 3
            },
            markPoint: {
              data: [
                { type: 'max', name: '最高气温' },
                { type: 'min', name: '最低气温' }
              ]
            },
          }
        ]
      };
    },
  },
  watch: {
    currentWeather(newVal) {
      console.log('WATCH: currentWeather changed to', newVal);
      // Debugging: Check the values of weather, humidity, and reporttime
      if (newVal) {
        console.log('currentWeather.weather:', newVal.weather);
        console.log('currentWeather.humidity:', newVal.humidity);
        console.log('currentWeather.reporttime:', newVal.reporttime);
      }
    },
    forecastWeather(newVal, oldVal) {
      console.log('WATCH: forecastWeather changed from', oldVal, 'to', newVal);
    },
    currentView: async function(newVal) {
      if (newVal === 'history') {
        this.historicalWeather = null;
        this.errorMessage = '';
        if (this.currentWeather && this.currentWeather.adcode) {
          this.location = this.currentWeather.adcode;
          this.date = new Date().toISOString().slice(0, 10);
          await this.fetchHistoricalWeather();
        } else {
          this.errorMessage = '请先在主页获取当前位置的天气信息。您也可以尝试搜索城市。';
          this.historicalWeather = null;
          this.location = '';
        }
      } else if (newVal === 'profile') {
        this.loadUserProfile();
      }
    },
    isLoggedIn: async function(newVal) {
      if (newVal) {
        this.currentView = 'home';
        console.log('frontend: 已登录，初始视图为home。');
        await this.getCurrentLocationAndWeather();
      } else {
        this.currentView = 'initial';
      }
    },
  },
  async created() {
    await this.checkLoginStatus();
    if (this.isLoggedIn) {
      this.currentView = 'home';
      console.log('frontend: 已登录，初始视图为home。');
      await this.getCurrentLocationAndWeather();
    } else {
      this.currentView = 'initial';
      console.log('frontend: 未登录，初始视图为initial。');
    }
    console.log('frontend: created方法执行完毕，currentView:', this.currentView);
    console.log('frontend: created方法执行完毕，selectedCity:', this.selectedCity);
  },
  methods: {
    getWeatherIconClass(description) {
      console.log('getWeatherIconClass: description received:', description);
      const iconMap = {
        '晴': '☀️',
        '多云': '⛅',
        '阴': '☁️',
        '阵雨': '🌦️',
        '雷阵雨': '⛈️',
        '小雨': '🌧️',
        '中雨': '🌧️',
        '大雨': '🌧️',
        '暴雨': '🌧️',
        '雨夹雪': '🌨️',
        '小雪': '🌨️',
        '中雪': '🌨️',
        '大雪': '🌨️',
        '暴雪': '🌨️',
        '雾': '🌫️',
        '霾': '😷',
        '浮尘': '💨',
        '沙尘暴': '💨',
        '大风': '💨',
      };
      return iconMap[description] || '❓';
    },
    async getCurrentLocationAndWeather() {
      this.locationLoading = true;
      this.locationError = null;
      try {
        if (!('geolocation' in navigator)) {
          throw new Error('您的浏览器不支持地理位置功能。');
        }

        const position = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject, { enableHighAccuracy: true });
        });

        const { latitude, longitude } = position.coords;
        console.log('获取到地理位置:', latitude, longitude);

        const detectedCity = await weatherService.getCityByCoordinates(latitude, longitude);
        console.log('frontend: 通过坐标检测到的城市:', detectedCity);

        if (detectedCity && detectedCity.city_id) {
          this.autoDetectedCity = detectedCity.name;
          this.selectedCity = detectedCity.city_id;
          await this.updateWeather();
          // 在获取到天气数据后立即获取AI建议
          await this.getAiSuggestions();
        } else {
          this.locationError = '未能检测到当前位置的城市。';
          alert('未能检测到当前位置的城市，请尝试手动搜索。');
        }
      } catch (error) {
        console.error('获取当前位置和天气失败:', error);
        this.locationError = '获取当前位置和天气失败：' + error.message;
        alert('获取当前位置和天气失败：' + error.message);
      } finally {
        this.locationLoading = false;
      }
    },
    async searchCity() {
      if (!this.searchQuery) {
        alert('请输入城市名称进行搜索。');
        return;
      }
      try {
        console.log('Searching for city:', this.searchQuery);
        const city = await weatherService.searchCityByName(this.searchQuery);
        if (city && city.city_id) {
          this.selectedCity = city.city_id;
          await this.updateWeather();
        } else {
          alert('未找到该城市，请尝试其他名称或联系管理员添加。');
        }
      } catch (error) {
        console.error('搜索城市失败:', error);
        alert('搜索城市失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    async loadCities() {
      try {
        console.log('开始加载城市列表...');
        this.cities = await weatherService.getCities();
        console.log('城市列表加载完成:', this.cities);
      } catch (error) {
        console.error('加载城市列表失败:', error);
      }
    },
    async updateWeather() {
      try {
        console.log('frontend: updateWeather被调用，selectedCity:', this.selectedCity);
        if (this.selectedCity) {
          console.log('获取城市天气:', this.selectedCity);
          this.currentWeather = await weatherService.getCityWeather(this.selectedCity);
          console.log('frontend: 天气信息加载完成，currentWeather:', this.currentWeather);
          
          // 获取未来天气预报
          try {
            this.forecastWeather = await weatherService.getCityForecast(this.selectedCity);
            console.log('frontend: 天气预报加载完成，forecastWeather:', this.forecastWeather);
            this.updateChartData();
          } catch (forecastError) {
            console.error('frontend: 获取未来天气预报失败:', forecastError);
            this.forecastWeather = null; // 确保失败时清空预报数据
          }
        } else {
          console.log('frontend: 未选择城市，不加载天气。');
          this.currentWeather = null;
          this.forecastWeather = null; // 确保未选择城市时清空预报数据
        }
      } catch (error) {
        console.error('更新天气信息失败:', error);
        this.currentWeather = null;
        this.forecastWeather = null; // 确保获取实时天气失败时清空预报数据
      }
    },
    updateChartData() {
      if (!this.forecastWeather || !this.forecastWeather.forecasts) return;
      
      const dates = [];
      const highTemps = [];
      const lowTemps = [];
      
      this.forecastWeather.forecasts.forEach(forecast => {
        dates.push(this.formatDateTime(forecast.date));
        highTemps.push(parseInt(forecast.day_temp));
        lowTemps.push(parseInt(forecast.night_temp));
      });
      
      this.chartOption = {
        ...this.chartOption,
        xAxis: {
          ...this.chartOption.xAxis,
          data: dates
        },
        series: [
          {
            ...this.chartOption.series[0],
            data: highTemps
          },
          {
            ...this.chartOption.series[1],
            data: lowTemps
          }
        ]
      };
    },
    async setAsDefault() {
      try {
        console.log('尝试设置默认城市为:', this.selectedCity);
        await weatherService.setDefaultCity(this.selectedCity);
        alert('默认城市设置成功！');
      } catch (error) {
        console.error('设置默认城市失败:', error);
        if (error.response) {
          alert('设置默认城市失败：' + (error.response.data?.error || '未知错误'));
        } else if (error.request) {
          alert('网络错误，请检查网络连接');
        } else {
          alert('设置默认城市失败：' + error.message);
        }
      }
    },
    formatDateTime(date) {
      console.log('formatDateTime: date received:', date);
      const d = new Date(date);
      console.log('formatDateTime: new Date(date) result:', d);
      return new Date(date).toLocaleString('zh-CN');
    },
    formatDateShort(date) {
      const d = new Date(date);
      return `${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
    },
    async checkLoginStatus() {
      const token = localStorage.getItem('token');
      if (token) {
        try {
          const userInfo = await userService.getMe();
          this.isLoggedIn = true;
          this.userProfile = userInfo;
          this.editableUsername = userInfo.username;
          console.log('frontend: checkLoginStatus - 用户已登录并获取资料:', userInfo.username);
        } catch (error) {
          console.error('frontend: checkLoginStatus - 验证token失败或获取用户信息失败:', error);
          this.logout();
        }
      } else {
        this.isLoggedIn = false;
        console.log('frontend: checkLoginStatus - 无token，用户未登录。');
      }
    },
    async login() {
      try {
        const response = await userService.login(this.loginForm.email, this.loginForm.password);
        localStorage.setItem('token', response.token);
        this.isLoggedIn = true;
        const userInfo = await userService.getMe();
        this.userProfile = userInfo;
        this.editableUsername = userInfo.username;
        this.currentView = 'home';
        this.loginForm = { email: '', password: '' };
        alert('登录成功！');
        await this.getCurrentLocationAndWeather();
      } catch (error) {
        console.error('登录失败:', error);
        alert('登录失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    async register() {
      try {
        await userService.register(this.registerForm.username, this.registerForm.email, this.registerForm.password);
        alert('注册成功！请登录。');
        this.currentView = 'login';
        this.registerForm = { username: '', email: '', password: '' };
      } catch (error) {
        console.error('注册失败:', error);
        alert('注册失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    logout() {
      userService.logout();
      this.isLoggedIn = false;
      this.userProfile = { username: '', email: '', avatar_url: null };
      this.currentView = 'initial';
      this.currentWeather = null;
      this.forecastWeather = null;
      this.favoriteCities = [];
      this.autoDetectedCity = null;
      this.selectedCity = null;
      alert('已成功退出登录。');
    },
    goBack() {
      this.currentView = 'initial';
    },
    goToHome() {
      this.currentView = 'home';
      this.getCurrentLocationAndWeather();
    },
    goToFavorites() {
      this.currentView = 'favorites';
      this.loadFavoriteCities();
    },
    goToHistory() {
      this.currentView = 'history';
    },
    goToProfile() {
      this.currentView = 'profile';
    },
    openAddCityModal() {
      this.showAddCityModal = true;
      this.addCitySearchQuery = '';
      this.addCitySearchResults = [];
    },
    closeAddCityModal() {
      this.showAddCityModal = false;
    },
    async searchCityToAdd() {
      if (!this.addCitySearchQuery) {
        alert('请输入城市名称进行搜索。');
        return;
      }
      try {
        const city = await weatherService.searchCityByName(this.addCitySearchQuery);
        if (city && city.city_id) {
          this.addCitySearchResults = [city];
        } else {
          this.addCitySearchResults = [];
          alert('未找到该城市。');
        }
      } catch (error) {
        console.error('搜索城市失败:', error);
        alert('搜索城市失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    async addFavoriteCity(cityId) {
      try {
        await userService.addFavoriteCity(cityId);
        alert('城市添加收藏成功！');
        this.closeAddCityModal();
        this.loadFavoriteCities();
      } catch (error) {
        console.error('添加收藏城市失败:', error);
        alert('添加收藏城市失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    async loadFavoriteCities() {
      try {
        const response = await userService.getFavoriteCities();
        if (response && response.cities) {
          this.favoriteCities = response.cities;
        } else {
          this.favoriteCities = [];
        }
        console.log('loadFavoriteCities: Favorite cities loaded:', this.favoriteCities);
      } catch (error) {
        console.error('加载收藏城市失败:', error);
        this.favoriteCities = [];
        alert('加载收藏城市失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    async viewFavoriteCityWeather(cityId) {
      try {
        this.selectedCity = cityId;
        this.currentView = 'home';
        await this.updateWeather();
        console.log('已切换到收藏城市并显示天气:', cityId);
      } catch (error) {
        console.error('获取城市天气失败:', error);
        alert('获取城市天气失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    async loadUserProfile() {
      try {
        const response = await userService.getMe();
        this.userProfile = response;
        this.editableUsername = response.username;
        console.log('[loadUserProfile] 用户资料加载成功:', this.userProfile);
      } catch (error) {
        console.error('加载用户资料失败:', error);
        alert('加载用户资料失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    startEditUsername() {
      this.isEditingUsername = true;
      this.editableUsername = this.userProfile.username;
    },
    async saveUsername() {
      try {
        await userService.updateProfile({ username: this.editableUsername });
        this.userProfile.username = this.editableUsername;
        this.isEditingUsername = false;
        alert('昵称更新成功！');
      } catch (error) {
        console.error('更新昵称失败:', error);
        alert('更新昵称失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    cancelEditUsername() {
      this.isEditingUsername = false;
      this.editableUsername = this.userProfile.username;
    },
    openChangePasswordModal() {
      this.showChangePasswordModal = true;
      this.oldPassword = '';
      this.newPassword = '';
      this.confirmNewPassword = '';
    },
    closeChangePasswordModal() {
      this.showChangePasswordModal = false;
      this.oldPassword = '';
      this.newPassword = '';
      this.confirmNewPassword = '';
    },
    async changePassword() {
      if (this.newPassword !== this.confirmNewPassword) {
        alert('两次输入的密码不一致！');
        return;
      }
      if (this.newPassword.length < 6) {
        alert('新密码长度不能少于6位。');
        return;
      }

      try {
        await userService.changePassword({
          oldPassword: this.oldPassword,
          newPassword: this.newPassword,
        });
        alert('密码修改成功，请重新登录！');
        this.closeChangePasswordModal();
        this.logout();
      } catch (error) {
        console.error('修改密码失败:', error);
        alert('修改密码失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    handleAvatarFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedAvatarFile = file;
        const reader = new FileReader();
        reader.onload = (e) => {
          this.previewAvatarUrl = e.target.result;
        };
        reader.readAsDataURL(file);
      } else {
        this.selectedAvatarFile = null;
        this.previewAvatarUrl = null;
      }
    },
    async uploadUserAvatar() {
      if (!this.selectedAvatarFile) {
        alert('请先选择一个头像文件。');
        return;
      }

      const formData = new FormData();
      formData.append('avatar', this.selectedAvatarFile);

      try {
        const response = await userService.uploadAvatar(formData);
        this.userProfile.avatar_url = response.avatar_url;
        this.selectedAvatarFile = null;
        this.previewAvatarUrl = null;
        alert('头像上传成功！');
      } catch (error) {
        console.error('上传头像失败:', error);
        alert('上传头像失败：' + (error.response?.data?.error || '未知错误'));
      }
    },
    async getAiSuggestions() {
      if (!this.currentWeather || !this.forecastWeather || !this.selectedCity) {
        alert('请先搜索并选择一个城市，以获取天气信息。');
        return;
      }

      this.aiLoading = true;
      this.aiSuggestions = null; // 清空之前的建议

      try {
        const response = await aiService.getAiSuggestions(
          this.currentWeather,
          this.forecastWeather.forecasts,
          this.currentWeather.city_name
        );
        this.aiSuggestions = response; // response 已经是解析后的 JSON 对象
        console.log('AI Suggestions received:', this.aiSuggestions);
      } catch (error) {
        console.error('获取AI建议失败:', error);
        alert('获取AI建议失败，请稍后再试。');
      } finally {
        this.aiLoading = false;
      }
    },
    async fetchHistoricalWeather() {
      if (!this.location) { // date is no longer required for the backend query
        this.errorMessage = '请输入城市。';
        return;
      }
      this.historicalWeather = null;
      this.errorMessage = '';
      try {
        // The backend now returns historical data from cache, not forecast
        const response = await weatherService.getHistoricalWeather(this.location, this.date); 
        if (response && response.historicalWeather && response.historicalWeather.length > 0) {
          this.historicalWeather = response; // Assign the entire response to historicalWeather
        } else {
          this.errorMessage = response.error || '没有找到历史天气数据。';
        }
      } catch (error) {
        console.error('获取历史天气失败:', error);
        this.errorMessage = '获取历史天气数据失败，请稍后再试。';
      }
    },
    async detectLocationAndFetchWeather() {
      this.locationLoading = true;
      this.locationError = '';
      try {
        if ("geolocation" in navigator) {
          navigator.geolocation.getCurrentPosition(async (position) => {
            const latitude = position.coords.latitude;
            const longitude = position.coords.longitude;
            
            try {
              const cityResponse = await weatherService.getCityByCoordinates(latitude, longitude);
              if (cityResponse && cityResponse.city_name) {
                this.autoDetectedCity = cityResponse.city_name;
                this.fetchWeatherByCityId(cityResponse.city_id); // Use the correct method to fetch weather by city ID
              } else {
                this.locationError = '无法通过坐标获取城市信息。';
              }
            } catch (cityError) {
              console.error('获取城市信息失败:', cityError);
              this.locationError = '获取城市信息失败，请检查网络或稍后再试。';
            }
          }, (error) => {
            console.error('Geolocation error:', error);
            this.locationError = '无法获取您的位置信息，请确保已授予位置权限。';
          });
        } else {
          this.locationError = '您的浏览器不支持地理位置服务。';
        }
      } finally {
        this.locationLoading = false;
      }
    },
    async fetchWeatherByCityId(cityId) {
      try {
        const weatherResponse = await weatherService.getCurrentWeather(cityId);
        if (weatherResponse && weatherResponse.lives && weatherResponse.lives.length > 0) {
          this.currentWeather = {
            city_name: weatherResponse.lives[0].city,
            province: weatherResponse.lives[0].province,
            adcode: weatherResponse.lives[0].adcode,
            temperature: weatherResponse.lives[0].temperature,
            weather: weatherResponse.lives[0].weather,
            winddirection: weatherResponse.lives[0].winddirection,
            windpower: weatherResponse.lives[0].windpower,
            humidity: weatherResponse.lives[0].humidity,
            reporttime: weatherResponse.lives[0].reporttime,
          };
        } else {
          this.locationError = '无法获取当前城市天气信息。';
        }

        const forecastResponse = await weatherService.getForecastWeather(cityId);
        if (forecastResponse && forecastResponse.forecasts && forecastResponse.forecasts.length > 0) {
          this.forecastWeather = {
            city_name: forecastResponse.forecasts[0].city,
            province: forecastResponse.forecasts[0].province,
            adcode: forecastResponse.forecasts[0].adcode,
            forecasts: forecastResponse.forecasts[0].casts.map(cast => ({
              date: cast.date,
              week: cast.week,
              day_weather: cast.dayweather,
              night_weather: cast.nightweather,
              day_temp: cast.daytemp,
              night_temp: cast.nighttemp,
              day_wind: cast.daywind,
              night_wind: cast.nightwind,
              day_power: cast.daypower,
              night_power: cast.nightpower,
            })),
          };
        }
      } catch (error) {
        console.error('获取天气信息失败:', error);
        this.locationError = '获取天气信息失败，请稍后再试。';
      }
    },
  }
};
</script>

<style scoped>
.weather-app {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f0f2f5;
  font-family: 'Arial', sans-serif;
  color: #333;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
}

.header-left span {
  font-size: 1.1em;
  font-weight: bold;
  color: #555;
}

.header-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  width: 180px;
  transition: width 0.3s ease, border-color 0.3s ease;
}

.search-input:focus {
  width: 220px;
  border-color: #07c160;
}

.search-button {
  padding: 8px 15px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.search-button:hover {
  background-color: #06ad57;
}

.add-city-button {
  padding: 8px 15px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.add-city-button:hover {
  background-color: #06ad57;
}

.app-main-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  text-align: center;
}

.weather-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #a1c4fd, #c2e9fb); /* 渐变背景 */
  border-radius: 15px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  color: #333;
  margin-bottom: 20px; /* 增加与下方模块的间距 */
}

.weather-display h2 {
  margin-bottom: 10px;
  font-size: 2.2em;
  color: #2c3e50;
}

.weather-display p {
  margin: 5px 0;
  font-size: 1.1em;
}

.weather-icon {
  font-size: 4em;
  margin-bottom: 15px;
  color: #f39c12; /* 醒目的图标颜色 */
}

.temperature {
  font-size: 3em;
  font-weight: bold;
  color: #e74c3c;
  margin-bottom: 5px;
}

.description {
  font-size: 1.3em;
  color: #555;
  margin-bottom: 10px;
}

.wind,
.humidity {
  font-size: 1em;
  color: #666;
}

.date {
  font-size: 0.9em;
  color: #777;
  margin-top: 15px;
}

.app-navbar {
  display: flex;
  justify-content: space-around;
  padding: 15px 20px;
  background-color: #ffffff;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
}

.app-navbar button {
  background-color: transparent;
  color: #555;
  border: none;
  padding: 10px 15px;
  cursor: pointer;
  font-size: 1.1em;
  transition: color 0.3s ease;
}

.app-navbar button:hover {
  color: #07c160;
}

.app-navbar button.active {
  color: #07c160;
  font-weight: bold;
  border-bottom: 2px solid #07c160;
}

.page-content {
  width: 100%;
  max-width: 600px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  text-align: center;
  margin-top: 20px;
}

.page-content h3 {
  font-size: 2em;
  margin-bottom: 20px;
  color: #333;
}

.auth-container {
  background: white;
  padding: 40px 30px;
  width: 320px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border-radius: 8px;
  text-align: center;
  margin: auto;
}

.auth-container h2 {
  margin-bottom: 30px;
  font-size: 28px;
  color: #333;
}

.welcome-text {
  font-size: 24px;
  margin-bottom: 30px;
  color: #333;
}

.auth-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.auth-buttons button {
  width: 100%;
  padding: 12px 0;
  background: #07c160;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  transition: background 0.3s ease;
}

.auth-buttons button:hover {
  background: #06ad57;
}

.form-group {
  margin-bottom: 25px;
}

.form-group input {
  width: 100%;
  padding: 12px 0;
  border: none;
  border-bottom: 1px solid #eee;
  background-color: transparent;
  outline: none;
  font-size: 16px;
  color: #333;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  border-bottom-color: #07c160;
}

button {
  width: 100%;
  padding: 12px 0;
  margin-top: 20px;
  background: #07c160;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  transition: background 0.3s ease;
}

button:hover {
  background: #06ad57;
}

button[type="button"] {
  background: transparent;
  color: #888;
  border: 1px solid #eee;
  margin-top: 10px;
  padding: 10px 0;
  font-size: 16px;
}

button[type="button"]:hover {
  background: #f0f0f0;
  color: #666;
}

.forecast-section {
  margin-top: 2rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
}

.forecast-list {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 2rem;
}

.forecast-item {
  flex: 1;
  min-width: 200px;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.forecast-date {
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.forecast-weather {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.day-weather, .night-weather {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.temperature-chart {
  margin-top: 2rem;
}

.chart {
  height: 400px;
  width: 100%;
}

.add-city-modal {
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
  max-width: 400px;
  border-radius: 8px;
}

.close-button {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close-button:hover,
.close-button:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

.city-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.city-item:last-child {
  border-bottom: none;
}

.city-item span {
  flex: 1;
}

.city-item button {
  padding: 5px 10px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.city-item button:hover {
  background-color: #06ad57;
}

.favorite-cities-list {
  margin-bottom: 20px;
}

.favorite-city-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.favorite-city-item:last-child {
  border-bottom: none;
}

.favorite-city-item span {
  flex: 1;
}

.favorite-city-item button {
  padding: 5px 10px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.favorite-city-item button:hover {
  background-color: #06ad57;
}

/* 新增样式：收藏页面头部布局 */
.favorites-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px; /* 调整间距 */
}

/* 历史天气列表样式 */
.historical-weather-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 20px;
}

.historical-weather-item {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.historical-weather-item p {
  margin: 5px 0;
  font-size: 0.95em;
  color: #333;
}

/* Profile Page Styles */
.profile-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  margin: 40px auto;
  text-align: center;
}

.profile-header h2 {
  color: #333;
  margin-bottom: 25px;
  font-size: 1.8em;
}

.profile-avatar {
  margin-bottom: 30px;
  position: relative; /* 允许内部元素定位 */
}

.avatar-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #4CAF50;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.avatar-upload-overlay {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  color: white;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 1.2em;
  transform: translate(25%, 25%); /* 调整位置使其在右下角 */
}

.avatar-upload-overlay:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.avatar-upload-input {
  display: none; /* 隐藏原始文件输入框 */
}

.profile-upload-button {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 15px;
  cursor: pointer;
  font-size: 0.9em;
  transition: background-color 0.3s ease;
  margin-top: 15px; /* 与头像的间距 */
}

.profile-upload-button:hover {
  background-color: #0056b3;
}

.profile-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  font-size: 1.1em;
  color: #555;
}

.profile-item:last-child {
  border-bottom: none;
}

.profile-item label {
  font-weight: bold;
  color: #333;
  flex-basis: 30%; /* 调整标签宽度 */
  text-align: left;
}

.profile-item span {
  flex-basis: 65%; /* 调整内容宽度 */
  text-align: right;
  word-break: break-all; /* 防止邮箱过长溢出 */
}

.editable-field {
  display: flex;
  align-items: center;
  flex-basis: 65%;
  justify-content: flex-end;
}

.editable-field input.edit-input {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 8px 10px;
  font-size: 1em;
  width: 150px; /* 调整输入框宽度 */
  margin-right: 10px;
}

.profile-item button {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 15px;
  cursor: pointer;
  font-size: 0.9em;
  transition: background-color 0.3s ease;
  margin-left: 10px; /* 按钮间距 */
}

.profile-item button:hover {
  background-color: #45a049;
}

.profile-item button.cancel-button {
  background-color: #f44336;
}

.profile-item button.cancel-button:hover {
  background-color: #da190b;
}

/* 修改密码和退出登录按钮 */
.change-password-button, .logout-button {
  display: block;
  width: 80%;
  padding: 12px;
  margin: 20px auto 10px auto; /* 调整间距 */
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1.1em;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.logout-button {
  background-color: #dc3545;
}

.change-password-button:hover {
  background-color: #0056b3;
}

.logout-button:hover {
  background-color: #c82333;
}

/* 修改密码模态框 */
.change-password-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.change-password-modal .modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  position: relative;
  width: 90%;
  max-width: 450px;
}

.change-password-modal h2 {
  margin-top: 0;
  color: #333;
  margin-bottom: 20px;
  font-size: 1.5em;
}

.change-password-modal .form-group {
  margin-bottom: 15px;
  text-align: left;
}

.change-password-modal .form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.change-password-modal .form-group input {
  width: calc(100% - 22px); /* 减去 padding 和 border */
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 1em;
}

.change-password-modal button {
  padding: 10px 20px;
  margin-top: 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1em;
  transition: background-color 0.3s ease;
}

.change-password-modal button.save-button {
  background-color: #28a745;
  color: white;
  margin-right: 10px;
}

.change-password-modal button.save-button:hover {
  background-color: #218838;
}

.change-password-modal button.cancel-button {
  background-color: #6c757d;
  color: white;
}

.change-password-modal button.cancel-button:hover {
  background-color: #5a6268;
}

.forecast-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex-direction: column;
  align-items: flex-start; /* 调整为左对齐 */
  margin-bottom: 10px;
}

.forecast-date {
  font-size: 1.1em;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  text-align: center; /* 居中日期 */
  width: 100%; /* 让日期占据整行 */
}

.forecast-weather {
  display: flex;
  flex-direction: column; /* 垂直排列白天和夜晚天气 */
  width: 100%; /* 占据整行 */
}

.day-weather,
.night-weather {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 元素之间分散对齐 */
  width: 100%;
  padding: 8px 0;
  border-bottom: 1px dashed #eee; /* 添加虚线分隔 */
}

.night-weather {
  border-bottom: none; /* 最后一个不显示下边框 */
}

.weather-icon {
  font-size: 1.5em;
  margin-right: 10px;
}

.temperature {
  font-size: 1.1em;
  font-weight: bold;
  color: #e44d26;
  margin-left: 10px; /* 与天气描述保持间距 */
}

.wind {
  font-size: 0.9em;
  color: #666;
  margin-left: auto; /* 推到最右边 */
}

.ai-suggestions-section {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
  padding: 25px;
  margin-top: 25px;
  margin-bottom: 25px;
  text-align: left;
  transition: all 0.3s ease;
}

.ai-suggestions-section h3 {
  color: #333;
  font-size: 1.6em;
  margin-bottom: 18px;
  border-bottom: 2px solid #4CAF50;
  padding-bottom: 10px;
}

.ai-suggestions-section p {
  line-height: 1.8;
  color: #555;
  margin-bottom: 12px;
}

.ai-suggestions-section strong {
  color: #2196F3;
}

.ai-suggestions-section ul {
  list-style-type: none;
  padding-left: 0;
}

.ai-suggestions-section li {
  background-color: #e8f5e9;
  border-left: 5px solid #81C784;
  margin-bottom: 10px;
  padding: 12px 15px;
  border-radius: 8px;
  font-size: 0.95em;
}

.ai-suggestions-section li:last-child {
  margin-bottom: 0;
}

.get-ai-suggestions-button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 25px;
  border: none;
  border-radius: 8px;
  font-size: 1.1em;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
  margin-top: 20px;
  display: block;
  width: fit-content;
  margin-left: auto;
  margin-right: auto;
}

.get-ai-suggestions-button:hover {
  background-color: #45a049;
  transform: translateY(-2px);
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin: 20px auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.history-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-width: 800px;
  margin: 20px auto;
}

.history-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.history-input-group input[type="text"],
.history-input-group input[type="date"] {
  flex-grow: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 1rem;
}

.history-input-group button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s ease;
}

.history-input-group button:hover {
  background-color: #0056b3;
}

.history-weather-display {
  background-color: #f9f9f9;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
}

.history-weather-display h4 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.5rem;
}

.history-weather-display p {
  margin-bottom: 8px;
  font-size: 1rem;
  color: #555;
}

.history-weather-display .date-info {
  font-weight: bold;
  color: #007bff;
}

.history-weather-display .weather-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 10px;
}

.history-weather-display .weather-detail-item {
  background-color: #e6f2ff;
  border-radius: 5px;
  padding: 10px 15px;
  font-size: 0.95rem;
  color: #0056b3;
}

.history-weather-display .weather-detail-item strong {
  color: #003f8c;
}

.history-error-message {
  color: #dc3545;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 5px;
  padding: 10px;
  margin-top: 15px;
  font-size: 0.9rem;
  text-align: center;
}

.historical-chart {
  width: 100%;
  height: 400px; /* Adjust height as needed */
  margin-top: 20px;
}
</style> 